import mq from '../mysql'
const md5 = require('md5-node')
const dayjs = require('dayjs')

export const getTime = () => dayjs().format('YYYY-MM-DD HH:mm:ss')
export const createToken = (name: string, contact: string) =>
  md5(name + contact + 'ccl_fs')
export const routerBottom = (ctx: any) =>
  (ctx.body = ctx.params.body || { status: true })
export const checkLogin = (ctx: { header: { token: string } }) => {
  const token = ctx.header.token
  /* 取token 没有则直接false 有则查询数据库 */
  /* 
    status
    msg
    info
    
  */
  return new Promise<{
    status: boolean
    data?: {
      name: string
      contact: string
    }
    msg?: string
  }>(async (resolve) => {
    if (!token)
      return resolve({
        status: false,
        msg: '未获取到token',
      })
    try {
      const users = await mq(
        `SELECT * FROM user WHERE token = '${token}' AND userStatus = 0`
      )
      if (users.length === 0)
        return resolve({
          status: false,
          msg: 'token异常',
        })
      return resolve({
        status: true,
        data: {
          name: users[0].name,
          contact: users[0].contact,
        },
      })
    } catch (error) {
      return resolve({
        status: false,
        msg: error,
      })
    }
  })
}
// 特定字符串
const STRCONST = '_STRCONSTYH'
export const STR = {
  stringify(str: string) {
    return str.replace(/\'/g, STRCONST)
  },
  parse(str: string) {
    const reg = new RegExp(`${STRCONST}`, 'g')
    return str.replace(reg, "'")
  },
}

